/*
 * 巴法云例程
 * 2022-06-26
 * QQ交流群：824273231
 * 官网https://bemfa.com 
 * app 远程控制教程：https://bemfa.blog.csdn.net/article/details/98478379
 * 微信小程序远程控制教程：https://bemfa.blog.csdn.net/article/details/107019002
 * esp8266-01/01s和其他版本一样，只是需要控制的引脚口不同，修改引脚口为0口就行，app和微信小程序是通用的，修改自己的uid和主题名称就行。
 * 本程序可同时支持小爱、天猫、小度、app、小程序、Google home 、amazon alexa、api接口、巴法控制台等同时控制。
 */
#include <ESP8266WiFi.h>
#include <Ticker.h>
#include <Servo.h>
#include <main.h>

//巴法云服务器地址默认即可
#define TCP_SERVER_ADDR "bemfa.com"
//服务器端口，tcp创客云端口8344
#define TCP_SERVER_PORT "8344"

//********************需要修改的部分*******************//

#define DEFAULT_STASSID  "xx"     //WIFI名称，区分大小写，不要写错
#define DEFAULT_STAPSW   "xx"  //WIFI密码
String UID = "xxx";  //用户私钥，可在控制台获取,修改为自己的UID
String TOPIC =   "xxx";         //主题名字，可在控制台新建


//**************************************************//



//最大字节数
#define MAX_PACKETSIZE 512
//设置心跳值30s
#define KEEPALIVEATIME 60*1000



//tcp客户端相关初始化，默认即可
WiFiClient TCPclient;
String TcpClient_Buff = "";
unsigned int TcpClient_BuffIndex = 0;
unsigned long TcpClient_preTick = 0;
unsigned long preHeartTick = 0;//心跳
unsigned long preTCPStartTick = 0;//连接
bool preTCPConnected = false;

Servo myservo;
int openDeg = 60;
int closeDeg = 120;
int minDeg =  90;

int closeDegHot = minDeg+10;
int openDegHot = minDeg-10;

//相关函数初始化
//连接WIFI
void doWiFiTick();
void startSTA();

//TCP初始化连接
void doTCPClientTick();
void startTCPClient();
void sendtoTCPServer(String p);






// =============== 房间灯控制 ============
Ticker minTicker;
Ticker closePwmTicker;
bool doOpenLight = false;

void initServo(){
  myservo.attach(D5, 500, 2500); 
  delay(200);
}

void closePwm(){
  myservo.detach();
  closePwmTicker.detach();

  // pinMode(D5, INPUT);
  Serial.println("closePwm");
  doOpenLight = false;
}

void gotoMinDeg(){
  Serial.println("gotoMinDeg");
  myservo.write(minDeg); 
  minTicker.detach();
  closePwmTicker.attach_ms(1000, closePwm);
}


void LightBtn_Callback(const String state) {
  beginFlash(1);
  if (state == "on") {
    Serial.println("on");

    //转到黄色光，需要连续开关两次
    pinMode(D5, OUTPUT); 
    digitalWrite(D5, HIGH);  //白色
    
    delay(1000);

    digitalWrite(D5, LOW);
    pinMode(D5, INPUT);

    delay(1000);

    pinMode(D5, OUTPUT); 
    digitalWrite(D5, HIGH); //灰白色

    // delay(1000);

    // digitalWrite(D5, LOW);
    // pinMode(D5, INPUT);

    // delay(1000);

    // pinMode(D5, OUTPUT); 
    // digitalWrite(D5, HIGH); //黄色

  } else if(state == "off"){
    Serial.println("off");
    digitalWrite(D5, LOW);
    pinMode(D5, INPUT); 
  }
}



/*
  *发送数据到TCP服务器
 */
void sendtoTCPServer(String p){
  
  if (!TCPclient.connected()) 
  {
    Serial.println("Client is not readly");
    return;
  }
  TCPclient.print(p);
  Serial.println("[Send to TCPServer]:String");
  Serial.println(p);
  preHeartTick = millis();//心跳计时开始，需要每隔60秒发送一次数据
}


/*
  *初始化和服务器建立连接
*/
void startTCPClient(){
  if(TCPclient.connect(TCP_SERVER_ADDR, atoi(TCP_SERVER_PORT))){
    Serial.print("\nConnected to server:");
    Serial.printf("%s:%d\r\n",TCP_SERVER_ADDR,atoi(TCP_SERVER_PORT));
    
    String tcpTemp="";  //初始化字符串
    tcpTemp = "cmd=1&uid="+UID+"&topic="+TOPIC+"\r\n"; //构建订阅指令
    sendtoTCPServer(tcpTemp); //发送订阅指令
    tcpTemp="";//清空
    
    preTCPConnected = true;
    TCPclient.setNoDelay(true);
  }
  else{
    Serial.print("Failed connected to server:");
    Serial.println(TCP_SERVER_ADDR);
    TCPclient.stop();
    preTCPConnected = false;
  }
  preTCPStartTick = millis();
}


/*
  *检查数据，发送心跳
*/
void doTCPClientTick(){
 //检查是否断开，断开后重连
   if(WiFi.status() != WL_CONNECTED) return;

  if (!TCPclient.connected()) {//断开重连

    if(preTCPConnected == true){

      preTCPConnected = false;
      preTCPStartTick = millis();
      Serial.println();
      Serial.println("TCP Client disconnected.");
      TCPclient.stop();
    }
    else if(millis() - preTCPStartTick > 1*1000)//重新连接
      startTCPClient();
  }
  else
  {
    if (TCPclient.available()) {//收数据
      char c =TCPclient.read();
      TcpClient_Buff +=c;
      TcpClient_BuffIndex++;
      TcpClient_preTick = millis();
      
      if(TcpClient_BuffIndex>=MAX_PACKETSIZE - 1){
        TcpClient_BuffIndex = MAX_PACKETSIZE-2;
        TcpClient_preTick = TcpClient_preTick - 200;
      }
    }
    if(millis() - preHeartTick >= KEEPALIVEATIME){//保持心跳
      preHeartTick = millis();
      Serial.println("--Keep alive:");
      sendtoTCPServer("cmd=0&msg=keep\r\n");
    }
  }
  if((TcpClient_Buff.length() >= 1) && (millis() - TcpClient_preTick>=200))
  {//data ready
    TCPclient.flush();
    Serial.print("Rev string: ");
    TcpClient_Buff.trim(); //去掉首位空格
    Serial.println(TcpClient_Buff); //打印接收到的消息
    String getTopic = "";
    String getMsg = "";
    if(TcpClient_Buff.length() > 15){//注意TcpClient_Buff只是个字符串，在上面开头做了初始化 String TcpClient_Buff = "";
          //此时会收到推送的指令，指令大概为 cmd=2&uid=xxx&topic=light002&msg=off
          int topicIndex = TcpClient_Buff.indexOf("&topic=")+7; //c语言字符串查找，查找&topic=位置，并移动7位，不懂的可百度c语言字符串查找
          int msgIndex = TcpClient_Buff.indexOf("&msg=");//c语言字符串查找，查找&msg=位置
          getTopic = TcpClient_Buff.substring(topicIndex,msgIndex);//c语言字符串截取，截取到topic,不懂的可百度c语言字符串截取
          getMsg = TcpClient_Buff.substring(msgIndex+5);//c语言字符串截取，截取到消息
          Serial.print("topic:------");
          Serial.println(getTopic); //打印截取到的主题值
          Serial.print("msg:--------");
          Serial.println(getMsg);   //打印截取到的消息值
    }

    if (getMsg == "on" || getMsg == "off") {
      LightBtn_Callback(getMsg);
    }
    TcpClient_Buff="";
    TcpClient_BuffIndex = 0;
  }
}

void startSTA(){
  WiFi.disconnect();
  WiFi.mode(WIFI_STA);
  WiFi.begin(DEFAULT_STASSID, DEFAULT_STAPSW);
}



/**************************************************************************
                                 WIFI
***************************************************************************/
/*
  WiFiTick
  检查是否需要初始化WiFi
  检查WiFi是否连接上，若连接成功启动TCP Client
  控制指示灯
*/
void doWiFiTick(){
  static bool connectingWifi = false; //是否正在连接wifi
  static bool wifiConnected = false; //是否已经连上wifi
  static uint32_t lastWiFiCheckTick = 0;

  if (!connectingWifi && !wifiConnected) {
    connectingWifi = true;
    beginFlash(-1);
    startSTA();
    Serial.printf("Heap size:%d\r\n", ESP.getFreeHeap());
  }

  if ( WiFi.status() == WL_CONNECTED ) {
    lastWiFiCheckTick = millis();
    if (wifiConnected == false) { //刚连上wifi，初始化tcp
      stopFlash();
      wifiConnected = true;
      connectingWifi = false; 
      Serial.print("\r\nGet IP Address: ");
      Serial.println(WiFi.localIP());
      startTCPClient();
    }
  } else {
    //未连接超过 5s，重连
    if (millis() - lastWiFiCheckTick > 5000 && !connectingWifi && wifiConnected) {
      Serial.print("\r\nwifi rebegin");
      wifiConnected = false;
    }
  }
}


// 初始化，相当于main 函数
void setup() {
  Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);

  pinMode(D5, INPUT);  
  Serial.println("Beginning...");
}

//循环
void loop() {
  doWiFiTick();
  doTCPClientTick();
}
